import { Upload, Button, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { useState, useMemo } from 'react';
import { PaperClipOutlined, DeleteOutlined } from '@ant-design/icons';
import { getFakeFileList } from '@/utils/utils';

import styles from './Upload.less';
import _ from 'lodash';
import {downLoadByFile} from "@/utils/download";

export default (props) => {
  const {
    defaultFileList = [],
    onChange = () => {},
    disabled = false,
    action = '/file/upload',
    name = 'file',
    text = '点击上传',
    showUploadList = true,
    showUploadIcon = true,
    button = true,
  } = props;
  const [files, setFiles] = useState([]);
  const token = sessionStorage.getItem('Authorization') || localStorage.getItem('Authorization');
  const fileList = useMemo(() => {
    if (files.length)
      return files.map((item) => {
        if (item.url) return item;
        return {
          ...item,
          url: item?.response?.data?.fileUrl || item?.response?.data || '',
        };
      });
    return getFakeFileList(defaultFileList);
  }, [files, defaultFileList]);

  function beforeUpload(file, fileList) {
    console.log(file);
    const name = _.first(file.name.split('.'));
    const ext = _.last(file.name.split('.')).toLowerCase();
    const isValidName = name.length <= 30;
    const isValidExt = props?.accept
      ? props.accept
        .split(',')
        .map((str) => str.replace('.', '').toLowerCase())
        .includes(ext)
      : true;
    const isLt5M = file.size / 1024 / 1024 < 5;

    if (!isValidName) {
      message.warn({
        content: '文件名过长，请控制在30字符以内。',
      }).then(r => {});;
      // message.warning('文件名过长，请控制在30字符以内!');
    } else if (!isLt5M) {
      message.warn({
        content: '上传文件过大，请上传5M以内。',
      }).then(r => {});;
      // message.warning('上传文件过大，请上传5M以内!');
    } else if (!isValidExt) {
      message.warn({
        content: `请提交后缀为${props?.accept?.split(',')?.join('，')}格式的文件。`,
      }).then(r => {});
      // message.warning(`请提交后缀为${props?.accept}格式的文件！`);
    }
    return isValidExt && isLt5M && isValidName ? true : Upload.LIST_IGNORE;
  }

  const onDownload = (file) => {
    downLoadByFile(file);
  };
  const prefix = {
    test: '/test',
    dev: '/',
    uat: '/uat',
  };
  return (
    <Upload
      {...props}

      name={name}
      // action={`${prefix[ENV]}${action}`}
      beforeUpload={beforeUpload}
      headers={{
        token: token || '',
      }}
      fileList={fileList}
      onChange={({ file, fileList: files }) => {
        setFiles(
          files.map((item) => ({
            ...item,
            url: item?.url || item?.response?.result?.fileUrl || '',
            id: item?.id || item?.response?.result?.id || '',
          })),
        );
        if (file.status !== 'uploading') {
          console.log(file, files);
          if (file?.response && file.status !== 'removed' && !file?.response?.success) {
            // message.error(file.response.result);
            message.error({
              content: file.response.result || file.response.message || '上传失败。',
            }).then(r => {});;
          }
          onChange({ file, fileList: files });
        }
      }}
      showUploadList={
        showUploadList && {
          showRemoveIcon: !disabled,
          showDownloadIcon: true,
        }
      }
      onDownload={onDownload}
    >
      {
        button? <Button disabled={disabled} icon={showUploadIcon ? <UploadOutlined /> : null} type={props.type || 'default'}>
          {text}
        </Button> : <UploadOutlined />
      }


    </Upload>
  );
};

const getFileUrl = (file) => file.url || file.fileUrl;
const getFileName = (file) => file.name || file.fileName;

export const UploadList = (props) => {
  const { files = [], showDeleteIcon = false, onDelete = () => {}, target = '_blank' } = props;
  return (
    <>
      {files?.map((file) => (
        <>
          <div className={styles.listItem}>
            <div className={`ant-upload-text-icon ${styles.icon}`}>
              <PaperClipOutlined />
            </div>
            <a
              className={styles.link}
              href={getFileUrl(file)}
              // href={'#'}
              target={target}
              title={getFileName(file)}
              // onClick={(e) => {
              //   e.preventDefault();
              //   handleFileDownload(file);
              // }}
            >
              {getFileName(file)}
            </a>
            {props.onDelete ? (
              <DeleteOutlined className={styles.delete} onClick={() => onDelete(file)} />
            ) : null}
          </div>
        </>
      )) || []}
    </>
  );
};
